package com.lingfengerick.commons.connect;

import com.lingfengerick.commons.constant.Constant;
import org.apache.commons.lang3.ObjectUtils;

import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.io.*;
import java.net.URL;

/**
 * https工具类
 *  @author lingfengerick
 * @since 2021/8/29 12:55 下午
 */
public class HttpsUtils {

    /**
    * post请求
    * @author  lingfengerick
    * @since 2021/10/28  10:31 下午
    * @param url 请求地址
    * @param sendMsg 发送消息
    * @param connectTimeOut 连接超时时间
    * @param readTimeOut 读取超时时间
    * @return String 返回结果
    * @throws Exception 抛出异常
    *
    */
    public static String doPost(String url , String sendMsg , int connectTimeOut , int readTimeOut) throws Exception {
        return httpMethodByStream(sendMsg , url , Constant.TYPE_POST , connectTimeOut , readTimeOut);
    }

    public static String doGet(String url , String sendMsg , int connectTimeOut , int readTimeOut) throws Exception {
        return httpMethodByStream(sendMsg , url , Constant.TYPE_GET , connectTimeOut , readTimeOut);
    }

    /**
     * https请求
     * @param sendMsg 发送的数据
     * @param accessUrl 访问的地址
     * @param requestMthod 请求方法
     * @param connectTimeout 连接超时时间
     * @param readTimeout 读取超时时间
     * @return 返回接收到的数据
     * @author : lingfengerick
     * @since  : 2019-10-24
     * @throws IOException io异常
     * @throws ClassNotFoundException 查不到类
     */
    public static String httpMethodByStream(String sendMsg , String accessUrl , String requestMthod ,
                                            int connectTimeout , int readTimeout) throws Exception {
        URL url;
        OutputStream outputStream = null;
        ObjectOutputStream objOutputStream = null;
        InputStream inputStream = null;
        ObjectInputStream objInputStream = null;
        HttpsURLConnection httpsUrlConnection=null;
        String resultStr;
        try {
            url = new URL(accessUrl);
            //获取连接
            httpsUrlConnection=(HttpsURLConnection) url.openConnection();
            httpsUrlConnection.setSSLSocketFactory(getSSLSocketFactory());
            httpsUrlConnection.setUseCaches(false);
            httpsUrlConnection.setDoInput(true);
            httpsUrlConnection.setDoOutput(true);
            httpsUrlConnection.setRequestMethod(requestMthod);
            httpsUrlConnection.setAllowUserInteraction(true);
            httpsUrlConnection.setConnectTimeout(connectTimeout);
            httpsUrlConnection.setReadTimeout(readTimeout);
            httpsUrlConnection.setRequestProperty("Content-Type" , "image/png");
            outputStream = httpsUrlConnection.getOutputStream();
            objOutputStream = new ObjectOutputStream(outputStream);
            objOutputStream.writeObject(sendMsg);
            objOutputStream.flush();
            objOutputStream.close();
            outputStream.flush();
            outputStream.close();
            inputStream = httpsUrlConnection.getInputStream();
            objInputStream = new ObjectInputStream(inputStream);
            Object object = objInputStream.readObject();
            resultStr = object.toString();
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            try {
                if (ObjectUtils.isNotEmpty(inputStream)){
                    inputStream.close();
                }
                if (ObjectUtils.isNotEmpty(objInputStream)){
                    objInputStream.close();
                }
                if (ObjectUtils.isNotEmpty(outputStream)){
                    outputStream.close();
                }
                if (ObjectUtils.isNotEmpty(objOutputStream)){
                    objOutputStream.close();
                }
                if (ObjectUtils.isNotEmpty(httpsUrlConnection)){
                    httpsUrlConnection.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultStr;
    }

    private final static class HttpsTrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    /**
    * 获取SSLSocketFactory
    * @author  lingfengerick
    * @since  2021/10/31  4:01 下午
    * @return SSLSocketFactory
    *
    */
    private static SSLSocketFactory getSSLSocketFactory(){
        SSLContext ctx = null;
        try {
            ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { new HttpsTrustManager() }, new SecureRandom());
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        assert ctx != null;
        return ctx.getSocketFactory();
    }

}
